/**
 * Copyright 2018-2019 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.loader;

import com.jianggujin.modulelink.config.JModuleConfig;
import com.jianggujin.modulelink.exception.JModuleLinkException;
import com.jianggujin.modulelink.magager.JModuleManagerSupport;
import com.jianggujin.modulelink.module.JModule;
import com.jianggujin.modulelink.util.JAssert;
import com.jianggujin.modulelink.util.JLogFactory;
import com.jianggujin.modulelink.util.JLogFactory.JLog;
import com.jianggujin.modulelink.util.JModuleClassLoader;
import com.jianggujin.modulelink.util.JModuleUtils;

/**
 * 模块加载器抽象实现
 * 
 * @author jianggujin
 *
 */
public abstract class JAbstractModuleLoader<T extends JModuleConfig> implements JModuleLoader<T> {

    private static final JLog logger = JLogFactory.getLog(JAbstractModuleLoader.class);
    private ClassLoader classLoader;

    @Override
    public JModule<T> load(T moduleConfig, JModuleManagerSupport<T> moduleManager) {
        JModule<T> module = null;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        // 获取模块的ClassLoader
        JModuleClassLoader moduleClassLoader = createModuleClassLoader(moduleConfig);
        try {
            Thread.currentThread().setContextClassLoader(moduleClassLoader);
            module = this.load(moduleConfig, moduleClassLoader, moduleManager);
            JAssert.checkNotNull(module, "load module is null.");
        } catch (Throwable e) {
            loadModuleError(moduleClassLoader);
            throw new JModuleLinkException("load module error.", e);
        } finally {
            Thread.currentThread().setContextClassLoader(loader);
        }

        logger.info("loading module complete：{}", moduleConfig);
        return module;
    }

    /**
     * 创建模块类加载器
     * 
     * @param moduleConfig 模块配置
     * @return 模块加载器
     */
    protected JModuleClassLoader createModuleClassLoader(JModuleConfig moduleConfig) {
        JModuleClassLoader moduleClassLoader = new JModuleClassLoader(moduleConfig.getModuleUrls(), getClassLoader());
        return this.customize(moduleClassLoader);
    }

    /**
     * 加载模块
     * 
     * @param moduleConfig      模块配置
     * @param moduleClassLoader 模块类加载器
     * @param moduleManager     模块管理器
     * @return 加载的模块
     * @throws Exception 加载出现异常
     */
    protected abstract JModule<T> load(T moduleConfig, JModuleClassLoader moduleClassLoader,
            JModuleManagerSupport<T> moduleManager) throws Exception;

    /**
     * 加载模块失败，此处可以做一些清理的事情
     * 
     * @param moduleClassLoader 模块类加载器
     */
    protected void loadModuleError(ClassLoader moduleClassLoader) {
        JModuleUtils.destroyQuietly(moduleClassLoader);
    }

    /**
     * 获得类加载器
     * 
     * @return 类加载器
     */
    public ClassLoader getClassLoader() {
        if (classLoader != null) {
            return classLoader;
        }
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 设置类加载器
     * 
     * @param classLoader 类加载器
     */
    public void setClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    /**
     * 自定义处理模块类加载器
     * 
     * @param moduleClassLoader
     * @return
     */
    protected JModuleClassLoader customize(JModuleClassLoader moduleClassLoader) {
        return moduleClassLoader;
    }
}
